package com.yxx.serviceaccount.receiver;

import com.yxx.kafkautil.constant.KafkaConstant;
import com.yxx.serviceaccount.service.RechargeInfoService;
import com.yxx.serviceaccount.service.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author yuxiangxun
 * @date 2025/3/18
 * @apiNote
 */
@Slf4j
@Component
public class AccountReceiver {
    @Autowired
    UserAccountService userAccountService;

    @Autowired
    private RechargeInfoService rechargeInfoService;

    /**
     * 监听消息并添加账户信息
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_USER_REGISTER)
    public void addUserAccount(ConsumerRecord<String,String> record){
        // 获取用户id
        Long userId = Long.parseLong(record.value());
        if(null == userId){
            return;
        }
        // 添加账户信息
        userAccountService.addfUserAccount(userId);
    }

    /**
     * 扣减锁定金额
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_MINUS)
    public void minus(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isEmpty(orderNo)) {
            return;
        }
        //扣减锁定金额
        userAccountService.minus(orderNo);
    }

    /**
     * 解锁锁定金额
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_UNLOCK)
    public void unlock(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isEmpty(orderNo)) {
            return;
        }
        //  调用解除锁定
        userAccountService.unlock(orderNo);
    }

    /**
     * 充值成功通知
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_RECHARGE_PAY_SUCCESS)
    public void rechargePaySuccess(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        log.info("充值成功通知: {}", orderNo);
        //通知更新用户账号
        rechargeInfoService.rechargePaySuccess(orderNo);
    }
}
